var baseUrl = require('../../utils/urllink.js')

//获取应用实例
var app = getApp()
Page({
  data: {
    userInfo: {},
    page:1,
    page_size:10,
    list:[],
    agent_type:0,
    showTopTips:false,
    showTopTips_zhuce:false,
    showTopTips_article:false,
    is_show:false,
    subscribe:0,
    hostimgs: app.globalData.hostimgs,
    pid2:0,
    pid3:0,
    showfilter: false,
    list_show:false,
    showfilterindex: 0,
    shuxing:["1"],
    filterdata: [],
    filterdata2: [],
    cateindex:0,
    searchlist:[],
  },

  //搜索条件 点击
  setFilterPanel:function(e){
    var that = this;
    var id = e.currentTarget.dataset.id;
    console.log(id)
    that.setData({
      showfilter:true,
      showfilterindex: id,
      list_show: false,
      pid2:id,
      pid3:0,
    })
    if(id > 0){
      console.log(id)
      //获取分类
      getfenlei2(that,id)
    }else{
      // 获取集合
      getindexlist(that, app.globalData.user_id, 1, that.data.page_size,id,0)
    }

  },
//搜索 空白区隐藏
  hideFilter:function(e){
    var that = this;
    var index = e.currentTarget.dataset.findex;
    console.log(index)
    that.setData({
      showfilter: false,
      showfilterindex: 0,
    })
  },
//搜索 点击条件1
  setCateIndex:function(e){
    var that = this;
    var cateindex = e.currentTarget.dataset.cateindex;
    var cateid = e.currentTarget.dataset.cateid;
    console.log(cateid)//一级分类id
    that.setData({
      cateindex: cateindex,
    })
    getfenlei2(that, cateid)//获取二级分类信息
  },
  //搜索 点击条件2
  setSubcateIndex:function(e){
    var that = this;
    var subcateindex = e.currentTarget.dataset.subcateindex;
    var subcateid = e.currentTarget.dataset.subcateid;
    that.setData({
      subcateindex: subcateindex,
      showfilter:false,
      filterdata:[],
      searchlist:[],
      cateindex:0,
    })
    //TODO 获取条件 分页查询数据

  },
  //搜索 分类点击完成
  setSubcateIndex2:function(e){
    var that = this;
    var id = e.currentTarget.dataset.id;
    var sid = e.currentTarget.dataset.sid;
    console.log(id)//获取分类的2级id
    console.log(sid)//获取分类的3级id
    that.setData({
      showfilter:false,
      pid2:id,
      pid3: sid,
    })
    // 获取集合
    getindexlist(that, app.globalData.user_id, 1, that.data.page_size, id,sid)
  },
  //消费者跳转到注册页面
  tozhuce:function(){
    wx.navigateTo({
      url: '../index/register',
    })
    
  },
  toarticle:function(){
    wx.navigateTo({
      url: '../index/article',
    })
  },
  onLoad: function () {
    var that = this


    //登录调用
    getApp().getUserInfo(function (userInfo, openid1) {
      //更新数据
      that.setData({
        userInfo: app.globalData.userInfo
      })
      that.setData({
        agent_type: app.globalData.agent_type,
        subscribe: app.globalData.subscribe,
      })
      // 获取集合
      getindexlist(that, app.globalData.user_id, 1, that.data.page_size,that.data.pid2,that.data.pid3)
    })
    //搜索 风格
    getfenlei(that, 100)

    //首页调用一次服务器核算的方法
    //getlogin_task()

  },
  onShow:function(){
    var that = this
    that.setData({
      agent_type: app.globalData.agent_type,
      subscribe: app.globalData.subscribe,
      userInfo: app.globalData.userInfo
    })

    //提示
    this.setData({
      article: '第一次来买手街束手无策吗？来看看小编给你准备的新手指南吧！',
      showTopTips_article: true
    })
    setTimeout(function () {
      that.setData({
        showTopTips_article: false
      });
      if (that.data.agent_type == 0) {
        that.setData({
          showTopTips_zhuce: true,
        })
      } else {
        that.setData({
          showTopTips_zhuce: false,
        })
      }
    }, 20000);

    
   if(that.data.list.length<=0 ){
     //console.log("--------------------------22222-------------------")
     // 获取集合
     //getindexlist(that, app.globalData.user_id, 1, that.data.page_size,that.data.pid2,that.data.pid3)
   }
    
  },

  //封面图片
  photoshow:function(){

  },

  //跳转到帮助关注页面
  toguanzhu:function(e){
  wx.navigateTo({
    url: '../index/guanzhu',
  })
  },
  //跳转到注册绑定页面
  toregister:function(e){
    wx.navigateTo({
      url: '../index/register',
    })
  },


  //预览图片
  previewImage:function(e){
    var that = this;
    var current = e.target.dataset.src;
    var index = e.target.dataset.index;
    var images = [];
    for(var i=0;i<that.data.list[index].gallery.length;i++){
      images[i] = that.data.hostimgs + that.data.list[index].gallery[i].image_url
    }
    console.log(current);
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: images // 需要预览的图片http链接列表  
    })  
  },

  /**
 * 页面相关事件处理函数--监听用户下拉动作
 */
  onPullDownRefresh: function () {
    var that = this
    that.setData({
      page:1,
      agent_type: app.globalData.agent_type,
    })

    // 获取集合 刷新
    getindexlist(that, app.globalData.user_id, 1, that.data.page_size,0,0)
    wx.showToast({
      title: '刷新',
    })
    that.setData({
      pid2:0,
      pid3:0,
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    // 获取集合
    getindexlist(that, app.globalData.user_id, that.data.page, that.data.page_size, that.data.pid2,that.data.pid3)
  },

  //b用户 选货 商品到店铺
  xuanhuo: function (event) {
    var that = this;
    var goods_id = event.currentTarget.dataset.goodsid;
    //console.log("goods_id" + goods_id)
    //console.log("shop_id" + app.globalData.shop_id)
    xuanhuo(that, app.globalData.shop_id, goods_id) 
  },

  //点赞 
  doc_like:function(event) {
    var that = this
    var goods_id = event.currentTarget.dataset.id;
    var is_proud = event.currentTarget.dataset.type;
    var index = event.currentTarget.dataset.index;
    console.log(is_proud)
    if (is_proud == 0 ){
      //用户点赞
      goods_proud_op(that, app.globalData.user_id, goods_id,index)


    }else{
      //用户取消点赞
      goods_proud_op(that, app.globalData.user_id, goods_id, index)


    }

  },
  //跳转到商品详细页面
  todetail:function(e){
    var that = this
    var goods_id = e.currentTarget.dataset.goodsid;
    wx.navigateTo({
      url: '../goods/detail?goods_id='+goods_id,
    })
  },
  //跳转到商铺集合
  toshangpu:function(e){
    var that = this
    var user_id = e.currentTarget.dataset.userid;
    var store_id = e.currentTarget.dataset.storeid;
    wx.navigateTo({
      url: '../goods/goods_otherlist?store_id='+store_id+'&user_id='+user_id,
    })

  },
  //跳转到用户信息页面
  touser:function(e){
    var that = this
    var user_id = e.currentTarget.dataset.userid;
    wx.navigateTo({
      url: '../mine/mine_other?user_id='+user_id,
    })
  },

  //转发
  onShareAppMessage:function(e){

  }


})


//首页调用一次服务器核算的方法
function getlogin_task() {
  //请求服务器
  wx.request({
    url: baseUrl +'seller/admin/login_task.html',
    data: {
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {'content-type': 'application/json'}, // 设置请求的 header
    success: function (res) {

    },
    fail: function () {},
    complete: function () {}
  })
}  

//获取发布商品集合
function getindexlist(that,user_id,page,page_size,pid2,pid3) {
  wx.showLoading({
    title: '加载中...',
  })
  //请求服务器
  wx.request({
    url: baseUrl +'weapp/Index/index.html',
    data: {
      user_id:user_id,
      page:page,
      page_size:page_size,
      pid2:pid2,
      pid3: pid3,
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: { 'content-type': 'application/json' }, // 设置请求的 header
    success: function (res) {
      console.log(res.data)
      if(res.data.code == -1){
        
      }else{
        if(page == 1){
          that.setData({
            list:res.data,
            page:page+1,
          })

          if(res.data.length<=0){

            that.setData({
              list_show:true,
            })
          }
        }else{
          var list = that.data.list;
          if (list.length <= 0) {
            that.setData({
              list_show: true,
            })
          }
          for(var i=0;i<res.data.length;i++){
            list.push(res.data[i])
          } 
          that.setData({
            list:list,
            page:page+1,
          })

        }
        that.setData({
          is_show:true,
        })
      }
      wx.hideLoading();
    },
    fail: function () { },
    complete: function () { }
  })
}

// 用户点赞 /取消点赞
function goods_proud_op(that, user_id, goods_id,index) {
  //请求服务器
  wx.request({
    url: baseUrl +'weapp/Users/goods_proud_op.html',
    data: {
      user_id: user_id,
      goods_id: goods_id,
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: { 'content-type': 'application/json' }, // 设置请求的 header
    success: function (res) {
      console.log(res.data)
      if(res.data.code == 0){

        //取消点赞
        var list = that.data.list;
        var prouds = list[index].proud;
        var is_dianzai1 = false;
        if (list[index].proud != null){
          for (var i = 0; i < list[index].proud.length; i++) {
            if (list[index].proud[i].user_id == user_id) {
              is_dianzai1 = true;
            }
          }
        }else{

        }

        if(is_dianzai1){
 
          list[index].is_proud = 0;
          list[index].proud_count = list[index].proud_count - 1
          for (var i = 0; i < prouds.length; i++) {
            if (list[index].proud[i].user_id == user_id) {
              //删除这条记录
              list[index].proud.splice(i, 1)
            }
          }
          that.setData({
            list: list,
          })
          wx.showToast({
            title: '取消点赞',
          })
        }
        
      }else{

        var list = that.data.list;
        var prouds = list[index].proud;
        var is_dianzai = true;

        if (list[index].proud != null){
          for (var i = 0; i < list[index].proud.length; i++) {
            if (list[index].proud[i].user_id == res.data.user_id) {
              is_dianzai = false;
            }
          }
        }
        if(is_dianzai){

          list[index].is_proud = 1;
          list[index].proud_count = list[index].proud_count + 1
          if (prouds.length <= 0) {
            list[index].proud[0] = res.data
          } else {

            list[index].proud.unshift(res.data)
          }
          that.setData({
            list: list,
          })
          wx.showToast({
            title: '赞+1',
          })
        }

      }
      

    },
    fail: function () { },
    complete: function () { }
  })
}


//判断用户是否点赞
function is_proud(that,user_id,goods_id){
  //请求服务器
  wx.request({
    url: baseUrl +'weapp/Users/is_proud.html',
    data: {
      user_id: user_id,
      goods_id: goods_id,
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: { 'content-type': 'application/json' }, // 设置请求的 header
    success: function (res) {
      console.log(res.data)
      
      
      if(res.data.code == 0){
          // 0=> 未点赞
      }else{
          // 1=> 已点赞
      }

    },
    fail: function () { },
    complete: function () { }
  })
}



// B选货 选择当前商品
function xuanhuo(that, shop_id, goods_id) {
  if (shop_id == 0) {
    wx.showModal({
      title: '提示',
      content: '请先完善店铺资料,才能选货。',
      showCancel: false,

      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.navigateTo({
            url: '../dianpu/savedianpu',
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  } else {


    //请求服务器
    wx.request({
      url: baseUrl + 'weapp/Goods/add_shop_goods.html',
      data: {
        shop_id: shop_id,
        goods_id: goods_id,

      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'content-type': 'application/json'
      }, // 设置请求的 header
      success: function (res) {
        console.log(res.data)
        if (res.data.code == -1) {
          //你已经添加过该商品啦！
          wx.showToast({
            title: '已添加该商品',
          })
        } else if (res.data.code == -2) {
          //当前商品不存在或已下架！
          wx.showToast({
            title: '商品不存在或已下架',
          })
        } else {
          wx.showToast({
            title: '选货成功',
            icon: 'success',
            duration: 2000
          })
        }
      },
      fail: function () {
      },
      complete: function () {
        // complete
      }
    })
  }
}




//获取分类
function getfenlei(that, pid) {
  that.setData({
    list_show: false,
  })
  wx.request({
    url: baseUrl + 'weapp/Goods/goods_category.html',
    data: {
      pid: pid,
    },
    success(res) {
      let list = []
      for (let item of res.data) {
        list.push({
          id: item.id,//id对应地区ID
          name: item.name//name对应地区名称
        })
      }
      that.setData({
        filterdata: list,
      })

    },
    fail(err) {

    }
  })
}


//获取分类
function getfenlei2(that,pid){
  that.setData({
    list_show: false,
  })
  wx.showLoading({
    title: '加载中...',
  })
  wx.request({
    url: baseUrl + 'weapp/Goods/goods_category.html',
    data: {
      pid: pid,
    },
    success(res) {
      console.log(res.data)
      let list = []
      for (let item of res.data) {
        list.push({
          id: item.id,//id对应地区ID
          name: item.name//name对应地区名称
        })
      }
      that.setData({
        filterdata2:list,
      })
      wx.hideLoading();
      
    },
    fail(err) {

    }
  })
}